import axios from 'axios';
import {
	useUserStore
} from '@/stores/user.js'
//1. 创建axios对象
const service = axios.create({
	baseURL:'http://localhost:3005',
	timeout:5000
});

//2. 请求拦截器
service.interceptors.request.use(config => {
    config.headers['Content-Type']='application/json;charset=utf-8'; //设置请求头
	const userStore = useUserStore();
	let token = userStore.token; //用户登录成功保留在pinia的accessToken
	if (token) { //等同于token!=undefined||token!=''
		config.headers['Authorization'] = token;
	}

	return config;
}, error => {
	console.log("error1",error)
	return Promise.reject(error)
	
});

//3. 响应拦截器
service.interceptors.response.use(response => {
	//判断code码
	// response.data 即为后端返回的Result
	let res=response.data;
	// 兼容服务端返回的字符串数据
	if(typeof res==="string"){
		res =res ?JSON.parse(res):res
	}
	return res;
}, error => {
	console.log("error2",error)
	return Promise.reject(error)
	
	
});


// post 请求

export const post=config=>{
	return service({
		...config,
		method:"post",
		data:config.data
	})
}

export default service;